package com.ficus.road.maintain.service;

import com.ficus.road.maintain.core.model.Car;
import com.ficus.road.maintain.core.model.CarVideoRecord;
import com.ficus.road.maintain.dao.CarDao;
import com.ficus.road.maintain.dao.CarVideoRecordDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hao.zhou1
 * @Since 2021/10/8 上午11:19
 */
@Service
@Slf4j
public class CarVideoRecordService {
    @Autowired
    private CarVideoRecordDao carVideoRecordDao;

    @Autowired
    private CarDao carDao;

    public CarVideoRecord findNextRecord(String carId, Long timestamp) {
        Criteria criteria = Criteria.where("car_id").is(carId).and("end_time").gt(timestamp);
        Query query = Query.query(criteria).skip(0).limit(1).with(new Sort(Sort.Direction.ASC, "end_time"));
        List<CarVideoRecord> carVideoRecordList = carVideoRecordDao.findByQuery(query);
        if (CollectionUtils.isNotEmpty(carVideoRecordList)) {
            return carVideoRecordList.get(0);
        }
        return null;
    }

    public List<Car> findCars(String date) {
        List<Car> result = new ArrayList<>();
        Criteria criteria = Criteria.where("date").is(date);
        List<String> carIds = carVideoRecordDao.findDistinctByQuery(new Query(criteria), "car_id");
        if (CollectionUtils.isNotEmpty(carIds)) {
            Query query = new Query(Criteria.where("id").in(carIds));
            query.fields().include("_id");
            query.fields().include("plate_no");
            result = carDao.findByQuery(query);
        }
        return result;
    }

    // 找到近一天的carVideoRecord
    public List<CarVideoRecord> findNextRecordByDate(String carId, Long timestamp, Long endTime) {
        Criteria criteria = Criteria.where("car_id").is(carId).and("end_time").gt(timestamp).lt(endTime);
        Query query = Query.query(criteria).with(new Sort(Sort.Direction.ASC, "end_time"));
        List<CarVideoRecord> carVideoRecordList = carVideoRecordDao.findByQuery(query);
        return carVideoRecordList;
    }

    /**
     * 找到这辆车的最后一个文件
     */
    public CarVideoRecord findLastRecord(String carId) {
        Criteria criteria = Criteria.where("car_id").is(carId);
        Query query = Query.query(criteria).skip(0).limit(1).with(new Sort(Sort.Direction.DESC, "end_time"));
        List<CarVideoRecord> carVideoRecordList = carVideoRecordDao.findByQuery(query);
        if (CollectionUtils.isNotEmpty(carVideoRecordList)) {
            return carVideoRecordList.get(0);
        }
        return null;
    }
}
